/*
 *@PluginName:onTickerTime
 *@author:CarlosO Carvlho
 *@created:28-11-2012
 *@version:1.0
 *@siteauthor:http://carlosocarvalho.com.br
 * 
 */

;
(function($, window, document, undefined) {
    var pluginName = 'onTickerTime',
            defaults = {
                update: function() {
                },
                pause: function() {
                },
                finish: function() {
                },
                date: !1,
                triggerdate: 'datatrigger',
                LeadingZero: true,
                DisplayFormat: "%%D%% Dias, %%H%% Horas, %%M%% Minutos, %%S%% Segundos.",
                CountActive: true,
                CountStepper: -1,
                tickerInterval: 1, ///seconds,
                until: 0
            };
    function Plugin(element, options) {

        this.element = element;
        this.options = $.extend({}, defaults, options);
        this._name = pluginName;
        this.init();
    }
    ;
    Plugin.prototype = {
        init: function() {
            var tg = $(this.element).attr(this.options.triggerdate) ? $(this.element).attr(this.options.triggerdate) : this.options.date;
            $(this.element).data('CountStepper', this.options.CountStepper);
            $(this.element).data('CountActive', this.options.CountActive);
            $(this.element).data('TargetDate', tg);
            $(this.element).data('TargetDateOrig', tg);
            $(this.element).data('TargetUntil', this.options.until);
            $.action = 'run';
            var diff = this._diff();
            if (diff > 0) {
                this._execute(diff);
            } else {
                this._renderHtml('-- -- -- -- --');
            }



        },
        _diff: function() {

            var CountStepper = Math.ceil($(this.element).data('CountStepper'));
            if (CountStepper == 0)
                $(this.element).data('CountActive', false);
            $(this.element).data('SetTimeOutPeriod', (Math.abs(CountStepper) - 1) * (this.options.tickerInterval * 1000) + 990);
            // putspan(BackColor, ForeColor);
            var th = $(this.element).data('TargetDate'),
                    dtime = th.split(' '),
                    dt = dtime['0'].split('-'),
                    time = dtime['1'].split(':');
            var dthen = new Date(dt['0'], dt['1'] - 1, dt['2'], time['0'], time['1'], time['2']);
            var dnow = new Date();


            if (CountStepper > 0)
                var ddiff = new Date(dnow - dthen);
            else
                var ddiff = new Date(dthen - dnow);
            return Math.floor(ddiff.valueOf() / 1000);
        },
        _getSeconds: function(secs, num1, num2) {

            var s = ((Math.floor(secs / num1)) % num2).toString();
            if (this.options.LeadingZero && s.length < 2)
                s = "0" + s;
            return s;
        },
        _execute: function(secs) {
            var DisplayFormat = this.options.DisplayFormat, self = this, DisplayStr = '';
            if (secs < 0) {
                this._finish();
                return;
            }

            if ($.action === 'reset') {
                secs = this._diff();
            }

            DisplayStr = DisplayFormat.replace(/%%D%%/g, this._getSeconds(secs, 86400, 100000));
            DisplayStr = DisplayStr.replace(/%%H%%/g, this._getSeconds(secs, 3600, 24));
            DisplayStr = DisplayStr.replace(/%%M%%/g, this._getSeconds(secs, 60, 60));
            DisplayStr = DisplayStr.replace(/%%S%%/g, this._getSeconds(secs, 1, 60));

            this._onTicker(secs, DisplayStr);
            if ($(self.element).data('CountActive'))
                setTimeout(function() {

                    self._update(secs + $(self.element).data('CountStepper'));
                }, $(this.element).data('SetTimeOutPeriod'));
        },
        _renderHtml: function(str) {
            $(this.element).html(str);
        },
        _onTicker: function(secs, html) {

            this._renderHtml(html);

        },
        _update: function(secs) {
            this.options.update(this.element, secs);
            $.action = 'run';
            if ($(this.element).data('TargetDate') !== $(this.element).data('TargetDateOrig')) {
                $.action = 'reset';
                $(this.element).data('TargetDateOrig', $(this.element).data('TargetDate'));
            }
            this._execute(secs);

        },
        _finish: function() {
            var self = this;
            self.options.finish(self.element);


        }
    };


    $.fn[pluginName] = function(options) {
        return this.each(function() {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
            }
        });
    };


})(jQuery, window, document);